package com.yuanfeng.order.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.excel.ExcelsUtil;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.order.OrderCommissionVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.order.dto.*;
import com.yuanfeng.order.entity.OrderCommissionEntity;
import com.yuanfeng.order.mapper.OrderCommissionMapper;
import com.yuanfeng.order.service.OrderCommissionService;
import com.yuanfeng.order.vo.TgUserInfoVO;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName OrderCommissionServiceImpl
 * @Description
 * @Author hyq
 * @Date 2023/7/14 9:42
 * @Version 1.0
 **/
@Service
public class OrderCommissionServiceImpl extends ServiceImpl<OrderCommissionMapper, OrderCommissionEntity>
        implements OrderCommissionService {
    @Override
    public ResponseResult queryVkUserListExp(VKUserDTO vkUser) {
        ResponseResult resp = new ResponseResult();
        UserInfoVO userInfoVO= ParseTokenUtils.getPlatformUser(vkUser.getToken());

        List<VKUserDTO> vkUserList = this.baseMapper.queryShopVkUser(vkUser);
        String[] title = {"微客昵称", "微客手机号", "商家店铺", "邀请人", "推广数", "分享数","推广佣金","分享佣金额","佣金总额","成为微客时间"};
        List<Map<String, String>> list = Lists.newArrayList();
        if (vkUserList.size() > 10000) {
            return ResponseResult.fail(BizCodeEnume.ORDER_EXP_FAIL);
        }
        for (VKUserDTO user : vkUserList) {
            user.setUserName(StrUtil.isEmpty(user.getUserNickname()) ? user.getUserName() : user.getUserNickname());
            Map<String,Object> vkUser1 = this.baseMapper.queryShopVkUser1(user.getUserId());
            if (vkUser1==null){
                user.setCommissionSharing(new BigDecimal(0.00));
                user.setPromotionCommission(new BigDecimal(0.00));
                user.setTotalCommission(new BigDecimal(0.00));

                BigDecimal b = new BigDecimal(user.getVar2());
                BigDecimal b2 = new BigDecimal(user.getVar3());
                BigDecimal yongji = b.add(b2);
                Double f = yongji.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                user.setYongJin(f.toString());
            }else {
                user.setCommissionSharing(new BigDecimal(vkUser1.get("commissionSharing").toString()));
                user.setPromotionCommission(new BigDecimal(vkUser1.get("promotionCommission").toString()));
                user.setTotalCommission(new BigDecimal(vkUser1.get("totalCommission").toString()));
            }
            Integer integer = this.baseMapper.selectCount(new LambdaQueryWrapper<OrderCommissionEntity>()
                                             .eq(OrderCommissionEntity::getShareUserId,user.getUserId())
                                             .eq(OrderCommissionEntity::getFxTg, CommonType.commonStatus.YES.getCode()));
            user.setShareNum(integer);

            BigDecimal b = new BigDecimal(user.getVar2());
            BigDecimal b2 = new BigDecimal(user.getVar3());
            BigDecimal yongji = b.add(b2);
            Double f = yongji.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            user.setYongJin(f.toString());

            HashMap<String, String> map = com.google.common.collect.Maps.newHashMap();
            map.put("微客昵称",user.getUserName()+"");
            map.put("微客手机号", user.getMobile()+"");
            map.put("商家店铺", user.getShopName()+"");
            map.put("邀请人", user.getShopUserName()+"");
            map.put("推广数",user.getInviteNum()+"");
            map.put("分享数",user.getShareNum()+"");
            map.put("推广佣金",user.getPromotionCommission() +"");
            map.put("分享佣金额",user.getCommissionSharing()+"");
            map.put("佣金总额", user.getTotalCommission()+"");
            map.put("成为微客时间",user.getCreateTime()+"");
            list.add(map);
        }
        // excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map = Maps
                .newHashMap();
        map.put("VkUserListExp", list);
        String url = ExcelsUtil.createExcel(title, map,
                new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8,9,10}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
        resp.setCode(1);
        resp.setData(url);

        return resp;
    }

    @Override
    public ResponseResult queryFxGoodsList(FxGoodsInfoDTO fxGoodsInfo) throws IllegalAccessException {
        Map data= ParseMapUtils.beanToMap(fxGoodsInfo);
        IPage<FxGoodsInfoDTO> page=this.baseMapper.queryFxGoodsList(new Query<FxGoodsInfoDTO>().getPage(data),
                fxGoodsInfo);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryVkUserList(VKUserDTO vkUser) throws IllegalAccessException {
        Map data= ParseMapUtils.beanToMap(vkUser);
        IPage<VKUserDTO> page=this.baseMapper.queryVkUserList(new Query<VKUserDTO>().getPage(data),
                vkUser);
        for (VKUserDTO user : page.getRecords()) {
            user.setUserName(StrUtil.isEmpty(user.getUserNickname()) ? user.getUserName() : user.getUserNickname());
            Map<String,Object> vkUser1 = this.baseMapper.queryShopVkUser1(user.getUserId());
            if (vkUser1==null){
                user.setCommissionSharing(new BigDecimal(0.00));
                user.setPromotionCommission(new BigDecimal(0.00));
                user.setTotalCommission(new BigDecimal(0.00));

                BigDecimal b = new BigDecimal(user.getVar2());
                BigDecimal b2 = new BigDecimal(user.getVar3());
                BigDecimal yongji = b.add(b2);
                Double f = yongji.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                user.setYongJin(f.toString());
            }else {
                user.setCommissionSharing(new BigDecimal(vkUser1.get("commissionSharing").toString()));
                user.setPromotionCommission(new BigDecimal(vkUser1.get("promotionCommission").toString()));
                user.setTotalCommission(new BigDecimal(vkUser1.get("totalCommission").toString()));
            }
            Integer integer = this.baseMapper.selectCount(new LambdaQueryWrapper<OrderCommissionEntity>()
                    .eq(OrderCommissionEntity::getShareUserId,user.getUserId())
                    .eq(OrderCommissionEntity::getFxTg, CommonType.commonStatus.YES.getCode()));
            user.setShareNum(integer);

            BigDecimal b = new BigDecimal(user.getVar2());
            BigDecimal b2 = new BigDecimal(user.getVar3());
            BigDecimal yongji = b.add(b2);
            Double f = yongji.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            user.setYongJin(f.toString());
        }
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult shopVkCommission(MallOrderDTO mallOrderQuery) {
        Page<OrderCommissionVO> page = new Page<>(mallOrderQuery.getPage(),mallOrderQuery.getLimit());
        IPage<OrderCommissionVO> orderCommissionList = this.baseMapper.queryShopUserCommissionList(page,mallOrderQuery);

        return ResponseResult.success(PageUtils.getPage(orderCommissionList));
    }

    @Override
    public ResponseResult queryCommissionSettle(FxOrderListDTO settleList) throws IllegalAccessException {
        UserInfoVO userInfo= ParseTokenUtils.getPlatformUser(settleList.getToken());
        settleList.setUserId(userInfo.getUserId());
        settleList.setSettleQuery(1);
        Map data= ParseMapUtils.beanToMap(settleList);
        IPage<OrderCommissionVO> page=this.baseMapper.queryTgSettleList(new Query<OrderCommissionVO>().getPage(data),
                settleList);
        Map<String,Object> resultMap = new HashMap<>(8);
        resultMap.put("commonPage",PageUtils.getPage(page));
        resultMap.put("totalCommission",page.getTotal());
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryTgUser(TgUserDTO tgUser) {
        UserInfoVO userInfo= ParseTokenUtils.getPlatformUser(tgUser.getToken());

        if(tgUser.getTodayState() == 1){
            tgUser.setPayTime(TimeStampUtil.getNowDate());
        }
        tgUser.setUserId(userInfo.getUserId());
        Page<TgUserInfoVO> page = new Page<>(tgUser.getPage(), tgUser.getLimit());
        IPage<TgUserInfoVO> tgUserInfoList = this.baseMapper.queryTodayTgUser(page,tgUser);

        return ResponseResult.success(PageUtils.getPage(tgUserInfoList));
    }

    @Override
    public ResponseResult queryTgUserDetail(TgUserDTO tgUser) {
        UserInfoVO userInfo= ParseTokenUtils.getPlatformUser(tgUser.getToken());

        if(tgUser.getTodayState() == 1){
            tgUser.setPayTime(TimeStampUtil.getNowDate());
        }
        tgUser.setUserId(userInfo.getUserId());
        Page<OrderCommissionVO> page = new Page<>(tgUser.getPage(), tgUser.getLimit());
        IPage<OrderCommissionVO> tgUserInfoList = this.baseMapper.queryTgUserDetail(page,tgUser);

        return ResponseResult.success(PageUtils.getPage(tgUserInfoList));
    }

    @Override
    public ResponseResult queryTodaySettle(FxOrderListDTO settleList) {
        UserInfoVO userInfo= ParseTokenUtils.getPlatformUser(settleList.getToken());

        settleList.setOrderStatus(2);
        settleList.setPayTime(TimeStampUtil.getNowDate());
        settleList.setUserId(userInfo.getUserId());
        settleList.setSettleQuery(1);
        Page<OrderCommissionVO> page = new Page<>(settleList.getPage(), settleList.getLimit());
        IPage<OrderCommissionVO> orderCommissionList = this.baseMapper.querySettleList(page,settleList);

        return ResponseResult.success(PageUtils.getPage(orderCommissionList));
    }

    @Override
    public ResponseResult queryCommissionOrder(FxOrderListDTO orderList) {
        UserInfoVO userInfo= ParseTokenUtils.getPlatformUser(orderList.getToken());

        orderList.setUserId(userInfo.getUserId());
        if(null != orderList.getOrderStatus() && orderList.getOrderStatus().intValue() == 6){
            orderList.setOrderStatus(null);
        }
        Page<OrderCommissionVO> page = new Page<>(orderList.getPage(), orderList.getLimit());
        IPage<OrderCommissionVO> orderCommissionList = this.baseMapper.querySettleList(page,orderList);

        return ResponseResult.success(PageUtils.getPage(orderCommissionList));
    }

    @Override
    public ResponseResult queryUserCommission(FxOrderListDTO settleList) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(settleList.getToken());
        settleList.setUserId(userInfo.getUserId());
        // 1.今日结算总额
        settleList.setDateType(2);
        settleList.setSettleState(1);
        // 统计 购买人和分享人 是绑定关系的 订单
        BigDecimal todaySettleCommission = this.baseMapper.queryTotalSettleAmount(settleList);
        if(null == todaySettleCommission){
            todaySettleCommission = new BigDecimal(0);
        }
        //统计 购买人和分享人 不是绑定关系的 订单
        BigDecimal todayNotBindSettleCommission = this.baseMapper.queryTotalNotBindSettleAmount(settleList);
        if(null == todayNotBindSettleCommission){
            todayNotBindSettleCommission = new BigDecimal(0);
        }
        todaySettleCommission = todaySettleCommission.add(todayNotBindSettleCommission);

        // 2.结算佣金 购买人和分享人 是绑定关系的 订单
        settleList.setDateType(null);
        BigDecimal settleCommission = this.baseMapper.queryTotalSettleAmount(settleList);
        if(null == settleCommission){
            settleCommission = new BigDecimal(0);
        }
        //统计 购买人和分享人 不是绑定关系的 订单
        BigDecimal settleNotBindCommission = this.baseMapper.queryTotalNotBindSettleAmount(settleList);
        if(null == settleNotBindCommission){
            settleNotBindCommission = new BigDecimal(0);
        }
        settleCommission = settleCommission.add(settleNotBindCommission);

        // 3.待结算佣金 购买人和分享人 是绑定关系的 订单
        settleList.setSettleState(0);
        BigDecimal unSettleCommission = this.baseMapper.queryTotalSettleAmount(settleList);
        if(null == unSettleCommission){
            unSettleCommission = new BigDecimal(0);
        }
        //购买人和分享人 不是绑定关系的 订单
        BigDecimal unSettleNotBindCommission = this.baseMapper.queryTotalNotBindSettleAmount(settleList);
        if(null == unSettleNotBindCommission){
            unSettleNotBindCommission = new BigDecimal(0);
        }
        unSettleCommission = unSettleCommission.add(unSettleNotBindCommission);


        // 4.累计佣金 购买人和分享人 是绑定关系的 订单
        settleList.setSettleState(1);
        BigDecimal totalCommission = this.baseMapper.queryTotalSettleAmount(settleList);
        if(null == totalCommission){
            totalCommission = new BigDecimal(0);
        }
        //购买人和分享人 不是绑定关系的 订单
        BigDecimal totalNotBindCommission = this.baseMapper.queryTotalNotBindSettleAmount(settleList);
        if(null == totalNotBindCommission){
            totalNotBindCommission = new BigDecimal(0);
        }
        totalCommission = totalCommission.add(totalNotBindCommission);


        // 5.今日预估收益 购买人和分享人 是绑定关系的 订单
        settleList.setSettleState(0);
        settleList.setOrderStatus(2);
        settleList.setPayTime(DateUtils.getNowDateToString());
        BigDecimal todayCommission = this.baseMapper.queryTotalSettleAmount(settleList);
        if(null == todayCommission){
            todayCommission = new BigDecimal(0);
        }
        //购买人和分享人 不是绑定关系的 订单
        BigDecimal todayNotBindCommission = this.baseMapper.queryTotalNotBindSettleAmount(settleList);
        if(null == todayNotBindCommission){
            todayNotBindCommission = new BigDecimal(0);
        }
        todayCommission = todayCommission.add(todayNotBindCommission);

        Map<String,BigDecimal> map = new HashMap<>(8);
        map.put("todaySettleCommission",null == todaySettleCommission?BigDecimal.ZERO:todaySettleCommission);
        map.put("settleCommission",null==settleCommission?BigDecimal.ZERO:settleCommission);
        map.put("unSettleCommission",null==unSettleCommission?BigDecimal.ZERO:unSettleCommission);
        map.put("totalCommission",null == totalCommission?BigDecimal.ZERO:totalCommission);
        map.put("todayCommission",null == todayCommission?BigDecimal.ZERO:todayCommission);
        return ResponseResult.success(map);
    }
}
